package com.shiyi.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.shiyi.io.Resources;
import com.shiyi.pojo.Configration;
import com.shiyi.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @Descrption
 * @Author: 十一
 * @Date: 2020-11-08 22:29
 * @Version V4.6
 **/
public class XMLConfigBuilder {

    private Configration configration;

    public XMLConfigBuilder() {
        this.configration = new Configration();
    }

    public Configration parse(InputStream in) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(in);
        Element rootElement = document.getRootElement();
        List<Element> propertyList = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : propertyList) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configration.setDataSource(comboPooledDataSource);
        // 解析mapper
        List<Element> mapperElementList = rootElement.selectNodes("//mapper");
        for (Element mapperElement : mapperElementList) {
            String resourcePath = mapperElement.attributeValue("resource");
            InputStream is = Resources.getResourceAsStream(resourcePath);
            new MapperConfigBuilder().parse(configration,is);
        }

        return configration;

    }
}
